package cn.yj.core.business.service;

import cn.yj.annotation.pagehelper.page.Page;
import cn.yj.cgs.dba.entity.Article;
import cn.yj.cgs.dba.entity.vo.ArticleVo;
import cn.yj.cgs.dba.mapper.ArticleMapper;
import cn.yj.common.Enums;
import cn.yj.commons.utils.FilterNull;
import cn.yj.commons.utils.MapUtils;
import cn.yj.params.check.annotation.CheckObjectValue;
import cn.yj.params.check.annotation.KeyValue;
import cn.yj.params.check.annotation.Require;
import cn.yj.tools.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author 永健
 * @since 2021-06-12 22:06
 */
@Service
public class ArticleService extends ServiceImpl<ArticleMapper, Article> {

    public Page<ArticleVo> pageList(@Require Map<String, Object> params, @Require Page<ArticleVo> page) {
        baseMapper.findListPc(params, page);
        return page;
    }

    public boolean deleteByNo(@Require String articleNo) {
        return baseMapper.delete(new UpdateWrapper<Article>().lambda().eq(Article::getArticleNo, articleNo)) > Enums.Common.ZERO;
    }

    /**
     * 更新审核状态
     *
     * @param body
     */
    @CheckObjectValue(keyValue = @KeyValue(type = Map.class, name = {"status", "articleNo"}))
    public boolean updateStatus(Map<String, Object> body) {
        Article article = baseMapper.selectOne(new QueryWrapper<Article>().lambda().eq(Article::getArticleNo,
                MapUtils.getStringVal(body, "articleNo")));
        FilterNull.isNull(article, "文章不存在");
        String status = MapUtils.getStringVal(body, "status");
        Enums.Article.STATUS[] values = Enums.Article.STATUS.values();

        // 状态类型校验
        boolean flag = false;
        for (int i = 0; i < values.length; i++) {
            Enums.Article.STATUS value = values[i];
            if (value.name().equals(status)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new ServiceException("审核状态异常");
        }
        Article a = new Article();
        a.setArticleNo(article.getArticleNo());
        a.setStatus(status);
        return super.update(a, new UpdateWrapper<Article>().lambda().eq(Article::getArticleNo, a.getArticleNo()));
    }
}
